
const { generateToken } = require('../utils/middleware')
const {userledger,sequelize,userInfo} = require('../dbConfig/index.js')
// 登录
const login = async (ctx,next)=>{
	const {user_phone,user_password} = ctx.request.body
	if(!(user_phone&&user_password)){
		ctx.body = {
			code:1,
			data:null,
			msg:'请输入用户名或密码'
		}
		return
	}
	if(user_phone==='15000000000'&&user_password==="admin123456"){
		ctx.body={
			code:200,
			data:{
				token:generateToken({user_id:0})
			},
			msg:'登录成功'
		}
		return
		}
	let userData = await userledger.findOne({where: {user_phone,user_password}})
	let res={}
	if(!userData){
		ctx.body = {code:1,data:null,msg:'用户名或密码错误'}
		return
	}
	res = {
		token:generateToken({user_id:userData.info_id})
	}
	ctx.body = {
		code:200,
		data:res,
		msg:'登录成功'
	}
}

const info = async(ctx,next)=>{
	const user_id = ctx.state.user_id
	let res = {}
	let code = 200
	let msg = ''
	if(user_id===0){
		res.identity = '0'
		msg = '超级管理员'
	}else{
		res =  await userInfo.findOne({where:{user_id:user_id}})
		msg = '成功'
	}
	ctx.body = {
		code:code,
		data:res,
		msg:msg
	}
	
}

const editPassword = async(ctx,next)=>{
	const {user_id,old_password,new_password} = ctx.request.body
	if(!(user_id&&old_password&&new_password)){
		ctx.body = {
			code:1,
			data:null,
			msg:'请输入完整信息'
		}
		return
	}
	let userData = await userledger.findOne({where: {Id:user_id,user_password:old_password}})
	if(!userData){
		ctx.body = {code:1,data:null,msg:'旧密码错误'}
		return
	}
	await userledger.update({user_password:new_password},{where:{Id:user_id}})
	ctx.body = {
		code:200,
		data:null,
		msg:'修改成功'
	}
}
module.exports = {
	login,
	info,
	editPassword
	// updataUserInfo,
	// checkUser,
	// getmerchantList
}